package com.education.ai.dao.impl;

import com.education.ai.dao.KnowledgePointDao;
import com.education.ai.entity.KnowledgePoint;
import com.education.ai.util.JdbcUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 知识点数据访问实现类
 */
@Repository
public class KnowledgePointDaoImpl implements KnowledgePointDao {

    private static final Logger logger = LoggerFactory.getLogger(KnowledgePointDaoImpl.class);
    
    @Autowired
    private JdbcUtil jdbcUtil;
    
    @Override
    public List<KnowledgePoint> findAll() {
        String sql = "SELECT * FROM knowledge_points";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql));
    }
    
    @Override
    public Optional<KnowledgePoint> findById(Long id) {
        String sql = "SELECT * FROM knowledge_points WHERE id = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, id);
        return results.isEmpty() ? Optional.empty() : Optional.of(mapRowToKnowledgePoint(results.get(0)));
    }
    
    @Override
    public List<KnowledgePoint> findByName(String name) {
        String sql = "SELECT * FROM knowledge_points WHERE name = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, name));
    }
    
    @Override
    public List<KnowledgePoint> findByNameContaining(String namePart) {
        String sql = "SELECT * FROM knowledge_points WHERE name LIKE ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, "%" + namePart + "%"));
    }
    
    @Override
    public List<KnowledgePoint> findBySubject(String subject) {
        String sql = "SELECT * FROM knowledge_points WHERE subject = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, subject));
    }
    
    @Override
    public List<KnowledgePoint> findByGrade(String grade) {
        String sql = "SELECT * FROM knowledge_points WHERE grade = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, grade));
    }
    
    @Override
    public List<KnowledgePoint> findBySubjectAndGrade(String subject, String grade) {
        String sql = "SELECT * FROM knowledge_points WHERE subject = ? AND grade = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, subject, grade));
    }
    
    @Override
    public List<KnowledgePoint> findByParentId(Long parentId) {
        String sql = "SELECT * FROM knowledge_points WHERE parent_id = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, parentId));
    }
    
    @Override
    public List<KnowledgePoint> findByLevel(Integer level) {
        String sql = "SELECT * FROM knowledge_points WHERE level = ?";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql, level));
    }
    
    @Override
    public List<KnowledgePoint> findRootKnowledgePoints() {
        String sql = "SELECT * FROM knowledge_points WHERE parent_id IS NULL OR parent_id = 0";
        return mapResultsToKnowledgePoints(jdbcUtil.executeQuery(sql));
    }
    
    @Override
    public KnowledgePoint save(KnowledgePoint knowledgePoint) {
        if (knowledgePoint.getId() == null) {
            // 插入操作
            String sql = "INSERT INTO knowledge_points (name, subject, grade, description, parent_id, level, create_time, update_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            if (knowledgePoint.getCreateTime() == null) {
                knowledgePoint.setCreateTime(now);
            }
            if (knowledgePoint.getUpdateTime() == null) {
                knowledgePoint.setUpdateTime(now);
            }
            
            long id = jdbcUtil.executeInsert(sql, 
                    knowledgePoint.getName(), 
                    knowledgePoint.getSubject(), 
                    knowledgePoint.getGrade(), 
                    knowledgePoint.getDescription(), 
                    knowledgePoint.getParentId(), 
                    knowledgePoint.getLevel(),
                    Timestamp.valueOf(knowledgePoint.getCreateTime()),
                    Timestamp.valueOf(knowledgePoint.getUpdateTime()));
            
            knowledgePoint.setId(id);
            return knowledgePoint;
        } else {
            // 更新操作
            update(knowledgePoint);
            return knowledgePoint;
        }
    }
    
    @Override
    public boolean update(KnowledgePoint knowledgePoint) {
        String sql = "UPDATE knowledge_points SET name = ?, subject = ?, grade = ?, description = ?, parent_id = ?, " +
                "level = ?, update_time = ? WHERE id = ?";
        
        // 设置更新时间
        knowledgePoint.setUpdateTime(LocalDateTime.now());
        
        int rows = jdbcUtil.executeUpdate(sql,
                knowledgePoint.getName(),
                knowledgePoint.getSubject(),
                knowledgePoint.getGrade(),
                knowledgePoint.getDescription(),
                knowledgePoint.getParentId(),
                knowledgePoint.getLevel(),
                Timestamp.valueOf(knowledgePoint.getUpdateTime()),
                knowledgePoint.getId());
        
        return rows > 0;
    }
    
    @Override
    public boolean deleteById(Long id) {
        String sql = "DELETE FROM knowledge_points WHERE id = ?";
        int rows = jdbcUtil.executeUpdate(sql, id);
        return rows > 0;
    }
    
    @Override
    public long count() {
        String sql = "SELECT COUNT(*) AS count FROM knowledge_points";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql);
        if (!results.isEmpty()) {
            return ((Number) results.get(0).get("count")).longValue();
        }
        return 0;
    }
    
    @Override
    public long countBySubject(String subject) {
        String sql = "SELECT COUNT(*) AS count FROM knowledge_points WHERE subject = ?";
        List<Map<String, Object>> results = jdbcUtil.executeQuery(sql, subject);
        if (!results.isEmpty()) {
            return ((Number) results.get(0).get("count")).longValue();
        }
        return 0;
    }
    
    /**
     * 将查询结果映射为知识点对象列表
     */
    private List<KnowledgePoint> mapResultsToKnowledgePoints(List<Map<String, Object>> results) {
        List<KnowledgePoint> knowledgePoints = new ArrayList<>();
        for (Map<String, Object> row : results) {
            knowledgePoints.add(mapRowToKnowledgePoint(row));
        }
        return knowledgePoints;
    }
    
    /**
     * 将单行结果映射为知识点对象
     */
    private KnowledgePoint mapRowToKnowledgePoint(Map<String, Object> row) {
        KnowledgePoint knowledgePoint = new KnowledgePoint();
        knowledgePoint.setId(((Number) row.get("id")).longValue());
        knowledgePoint.setName((String) row.get("name"));
        knowledgePoint.setSubject((String) row.get("subject"));
        knowledgePoint.setGrade((String) row.get("grade"));
        knowledgePoint.setDescription((String) row.get("description"));
        
        if (row.get("parent_id") != null) {
            knowledgePoint.setParentId(((Number) row.get("parent_id")).longValue());
        }
        
        if (row.get("level") != null) {
            knowledgePoint.setLevel(((Number) row.get("level")).intValue());
        }
        
        if (row.get("create_time") != null) {
            Timestamp timestamp = (Timestamp) row.get("create_time");
            knowledgePoint.setCreateTime(timestamp.toLocalDateTime());
        }
        
        if (row.get("update_time") != null) {
            Timestamp timestamp = (Timestamp) row.get("update_time");
            knowledgePoint.setUpdateTime(timestamp.toLocalDateTime());
        }
        
        return knowledgePoint;
    }
} 